package wortubung.util;

import org.json.JSONArray;
import org.json.JSONObject;

import static wortubung.util.CommonUtils.*;

public class JSONUtils {

	public static Integer[] getIntArray(JSONObject json, String key) {
		JSONArray ja = json.optJSONArray(key);
		if (ja == null)
			return null;
		Integer[] ia = new Integer[ja.length()];
		for (int i=0; i<ia.length; ++i)
			ia[i] = ja.isNull(i) ? null : Integer.valueOf(ja.get(i).toString());
		return ia;
	}

	public static String[] getStringArray(JSONObject json, String key) {
		Object obj = json.opt(key);
		if (obj == null)
			return null;
		if (obj instanceof String)
			return new String[]{ (String)obj };
		JSONArray ja = (JSONArray)obj;
		String[] sa = new String[ja.length()];
		for (int i=sa.length-1; i>=0; --i)
			sa[i] = ja.isNull(i) ? null : ja.get(i).toString();
		return sa;
	}

	public static String getString(JSONObject json, String key, String defaultValue) {
		return json.has(key) && !json.isNull(key)? json.getString(key) : defaultValue;
	}

	public static boolean getBoolean(JSONObject json, String key) {
		return json.has(key) && json.getBoolean(key);
	}

	public static String trimJSONArrayEndingNulls(String line, boolean maintainEmptySpace) {
		int left = line.indexOf('[');
		int right = line.indexOf(']');
		String last = line.substring(right);
		String tmp = line.substring(left, right).trim();
		boolean trimmed = false;
		while (tmp.endsWith(", null")) {
			tmp = tmp.substring(0, tmp.length() - 6).trim();
			trimmed = true;
		}
		if (trimmed) {
			String fill = " ";
			if (maintainEmptySpace)
				fill = makeLine(' ', right-left-tmp.length());
			line = line.substring(0, left) + tmp + fill + last;
		}
		return line;
	}

	public static String[] toStringArray(JSONArray jsonArr) {
		if (jsonArr == null)
			return null;
		String[] ret = new String[jsonArr.length()];
		for (int i=ret.length-1; i>=0; --i)
			ret[i] = jsonArr.getString(i);
		return ret;
	}

	public static String toJSONArray(String[] sa, boolean trimEndingNulls) {
		StringBuilder sb = new StringBuilder("[ ");
		for (int i=0; i<sa.length; ++i) {
			if (i > 0)
				sb.append(", ");
			sb.append(qs(sa[i]));
		}
		sb.append(" ]");
		String ret = sb.toString();
		if (trimEndingNulls)
			return trimJSONArrayEndingNulls(ret, false);
		return ret;
	}
}
